package com.zhiwang.xiaoqu.ui.main


import android.annotation.SuppressLint
import android.app.AlertDialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.graphics.drawable.AnimationDrawable
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewpager.widget.ViewPager
import com.zhiwang.xiaoqu.R
import com.zhiwang.xiaoqu.bus.TabChangeEvent
import com.zhiwang.xiaoqu.di.annotation.Injectable
import com.zhiwang.xiaoqu.di.component.DaggerUserComponent
import com.zhiwang.xiaoqu.di.module.AutoDisposeModule
import com.zhiwang.xiaoqu.mvp.model.Store
import com.zhiwang.xiaoqu.mvp.model.response.IndexUserInfo
import com.zhiwang.xiaoqu.mvp.presenter.UserPresenter
import com.zhiwang.xiaoqu.ui.BaseFragment
import com.zhiwang.xiaoqu.ui.WebViewActivity
import com.zhiwang.xiaoqu.ui.coupon.DailyCheckInActivity
import com.zhiwang.xiaoqu.widget.SimpleDialog
import com.zhiwang.xiaoqu.widget.loopviewpager.LoopViewPager
import com.zhiwang.xiaoqu.widget.loopviewpager.SimpleNetWorkLoopingPagerAdapter
import com.zhiwang.xiaoqu.widget.transformer.ViewPagerGalleryTransform
import io.reactivex.Flowable
import io.reactivex.FlowableSubscriber
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.daily_red_packet.view.*
import kotlinx.android.synthetic.main.fragment_money.*
import org.greenrobot.eventbus.EventBus
import org.reactivestreams.Subscription
import quickStartActivity
import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Named

/**
 * A simple [Fragment] subclass.
 */
class MoneyFragment : BaseFragment(), SimpleDialog.OnDismissListener, Injectable {

    val TAG = "MoneyFragment"

    private lateinit var simpleDialog: SimpleDialog

    var onFragmentInteractionListener: OnFragmentInteractionListener? = null


    @Inject
    @JvmField
    @field:Named("count_time")
    var remainingTime: Int = 0

    @Inject
    lateinit var userPresenter: UserPresenter


    override fun onAttach(context: Context) {
        super.onAttach(context)
        if (context is OnFragmentInteractionListener)
            onFragmentInteractionListener = context
    }


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(R.layout.fragment_money, container, false)
    }


    override fun onStart() {
        super.onStart()
        (iv_daily_tasks.drawable as AnimationDrawable).start()


        vp_banner.adapter = SimpleNetWorkLoopingPagerAdapter(
            requireContext(),
            arrayListOf(
                "https://github.com/devWilly/InfiniteViewPagerEx/blob/master/app/src/main/res/drawable-xhdpi/pic1.png?raw=true",
                "https://github.com/devWilly/InfiniteViewPagerEx/blob/master/app/src/main/res/drawable-xhdpi/pic3.png?raw=true",
                "https://github.com/devWilly/InfiniteViewPagerEx/blob/master/app/src/main/res/drawable-xhdpi/pic2.png?raw=true"
            )
            , true
        )
        vp_banner.setPageTransformer(false, ViewPagerGalleryTransform())
        vp_banner.setIndicatorPageChangeListener(object :
            LoopViewPager.IndicatorPageChangeListener {

            override fun onIndicatorPageChange(newIndicatorPosition: Int) {
                banner_indicator.position = newIndicatorPosition
            }

            override fun onIndicatorProgress(selectingPosition: Int, progress: Float) {

            }

        })

        iv_daily_tasks.setOnClickListener {
            onFragmentInteractionListener?.onShowDailyRecommendTask()
        }

        iv_reward_nav.setOnClickListener { quickStartActivity(DailyCheckInActivity::class.java) }

        //快速任务
        fast_task.setOnClickListener {
            WebViewActivity.load(requireContext(), Store.URL_FAST_TASKS)
        }
        //应用赚
        app_task.setOnClickListener { WebViewActivity.load(requireContext(), Store.URL_APP_TASKS) }

        //游戏赚

        game_task.setOnClickListener {
            WebViewActivity.load(
                requireContext(),
                Store.URL_GAME_TASKS
            )
        }

        //赏金赛

        //正在进行
        task_running.setOnClickListener {

            simpleDialog = SimpleDialog.Builder(requireContext())
                .title("领奖提示")
                .descText(
                    "1.安装xxxx\n" +
                            "2.打开app，在规定时间按要求体验\n" +
                            "3.完成后，领取奖励"
                )
                .descTextSizeSp(14f)
                .cancellable(true)
                .singleButton(true)
                .singleButton("了解（3s）", 16f, R.drawable.btn_w550, R.color.colorWhite1)
                .setOnDismissListener(this)
                .create()
            simpleDialog
                .show()

            remainingTime = 3
            startTick()
        }

        //签到红包
        signin_redpacket.setOnClickListener {
            showDailySignInRedPacket()
        }
        userPresenter.getIndexInfo(::onLoadIndexInfo, ::onError)
    }

    @SuppressLint("AutoDispose")
    private fun startTick() {
        Flowable.interval(1, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.computation())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : FlowableSubscriber<Long> {

                var subscription: Subscription? = null

                override fun onSubscribe(s: Subscription) {
                    subscription = s
                    subscription?.request(1)
                }

                override fun onComplete() {
                }

                override fun onNext(t: Long?) {
                    if (remainingTime == 1) {
                        simpleDialog.dismiss()
                        subscription?.cancel()
                    }
                    simpleDialog.singleButton()?.text = "了解（${--remainingTime}s）"
                    subscription?.request(1)
                }

                override fun onError(t: Throwable?) {
                }

            })
    }

    override fun onDismiss(dialog: DialogInterface) {

    }

    fun onLoadIndexInfo(indexUserInfo: IndexUserInfo) {
        tv_balance.text = indexUserInfo.balance.plus("元")
        tv_profit.text = indexUserInfo.profit.plus("元")
    }


    private fun showDailySignInRedPacket() {
        val rootView = layoutInflater.inflate(R.layout.daily_red_packet, null)

        val dialog = AlertDialog.Builder(requireContext())
            .setView(rootView)
            .create()
        dialog.show()

        dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))

        rootView.tv_red_packet_num.text = "5.0"

        rootView.open_red_packet_btn.setOnClickListener {
            EventBus.getDefault().post(TabChangeEvent(1))
            dialog.dismiss()
        }

    }


    interface OnFragmentInteractionListener {

        fun onShowDailyRecommendTask()
    }

}
